import RankItem from "./RankItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Rank extends cc.Component {

    @property(cc.Node)
    private content: cc.Node = null;

    @property(cc.Prefab)
    private itemPrefab: cc.Prefab = null;

    @property(cc.Node)
    private loading: cc.Node = null;

    private selfColor: cc.Color = new cc.Color(246, 221, 141);
    private otherColor: cc.Color = new cc.Color(246, 221, 141);

    onLoad() {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME_SUB) return;
        wx.onMessage((msg: any) => this.onMessage(msg));
    }

    private onMessage(msg: any) {
        switch (msg.event) {
            case 'setScore':
                this.setScore(msg.score);
                break;
            case 'getRank':
                this.getRank();
                break;
        }
    }

    private getScore(): Promise<number> {
        return new Promise(resolve => {
            console.log('getScore')
            wx.getUserCloudStorage({
                keyList: ['score'],
                success: (res: UserGameData) => {
                    console.log('-success', res)
                    if (res.KVDataList.length > 0) resolve(parseInt(res.KVDataList[0].value));
                    else resolve(0);
                },
                fail: (res: any) => {
                    console.log('-fail', res)
                    resolve(-1);
                }
            });
        });
    }

    private async setScore(value: number) {
        console.log('setScore')
        let oldScore = await this.getScore();
        if (oldScore === -1) return;
        console.log('-oldScore', oldScore)
        console.log('-newScore', value)
        if (value > oldScore) {
            wx.setUserCloudStorage({
                KVDataList: [{ key: 'score', value: value.toString() }],
                success: (res: any) => {
                    console.log('-success', res)
                },
                fail: (res: any) => {
                    console.log('-fail', res)
                }
            });
        }
    }

    private getRank() {
        console.log('getRank')
        this.showLoading();
        wx.getFriendCloudStorage({
            keyList: ['score'],
            success: (res: any) => {
                console.log('-success', res)
                res.data.sort((a: UserGameData, b: UserGameData) => {
                    if (a.KVDataList.length === 0 && b.KVDataList.length === 0) return 0;
                    if (a.KVDataList.length === 0) return 1;
                    if (b.KVDataList.length === 0) return -1;
                    return parseInt(b.KVDataList[0].value) - parseInt(a.KVDataList[0].value);
                });
                this.updateList(res.data);
            },
            fail: (res: any) => {
                console.log('-fail', res)
            },
            complete: () => {
                console.log('-complete')
                this.hideLoading();
            }
        });
    }

    private updateList(list: UserGameData[]) {
        let count = Math.max(list.length, this.content.childrenCount);
        for (let i = 0; i < count; i++) {
            if (list[i] && this.content.children[i]) {
                this.content.children[i].active = true;
                this.content.children[i].getComponent(RankItem).set(i + 1, list[i]);
            } else if (list[i] && !this.content.children[i]) {
                let node = cc.instantiate(this.itemPrefab);
                node.getComponent(RankItem).set(i + 1, list[i]);
                node.setParent(this.content);
            } else {
                this.content.children[i].active = false;
            }
        }
    }

    private showLoading() {
        this.loading.active = true;
    }

    private hideLoading() {
        this.loading.active = false;
    }
}
